opt_out_usage
default_platform(:ios)

platform :ios do
  before_all do
    # Perform a fetch before inferring the next version
    # to reduce race conditions with simultaneous pipelines attempting to create the same tag
    sh('git', 'fetch', '--tags', '-f')
    sh('git', 'fetch')
  end

  desc "Create a pre-release version by pushing a tag to GitHub"
  lane :unstable do
    next_version = calculate_next_canary_version

    UI.message("Releasing unstable version: #{next_version}")

    # Increment all specs and plists
    increment_versions(version: next_version)

    # Create tag and push to origin
    add_tag(version: next_version)

  end

  desc "Create a release version by building and committing a changelog, pushing a tag to GitHub"
  lane :release do
    next_version, commits = calculate_next_release_version

    UI.message("Releasing version: #{next_version}")

    # Increment all specs and plists
    increment_versions(version: next_version)

    changelog = build_changelog(version: next_version, commits: commits)

    # Commit and push
    release_commit(version: next_version)

    # Create tag and push to origin
    add_tag(version: next_version)

    post_release(version: next_version, changelog: changelog)
  end

  desc "Increment versions"
  private_lane :increment_versions do |options|
    version = options[:version].to_s
    configuration_file_path = "AmplifyPlugins/Core/AmplifyCredentials/AmplifyAWSServiceConfiguration.swift"
    set_key_value(file: configuration_file_path, key: "amplifyVersion", value: version)
  end

  desc "Commit and push"
  private_lane :release_commit do |options|
    next_version = options[:version]

    sh('git', 'config', '--global', 'user.email', ENV['GITHUB_EMAIL'])
    sh('git', 'config', '--global', 'user.name', ENV['GITHUB_USER'])

    commit_message = "chore: release #{next_version} [skip ci]"
    sh('git', 'commit', '-am', commit_message)

    # push to origin
    sh('git', 'push', 'origin', 'release')
  end

  desc "Tag in git and push to GitHub"
  private_lane :add_tag do |options|
    next_version = options[:version]
    next_tag = "#{next_version}"

    add_git_tag(tag: next_tag)
    push_git_tags(tag: next_tag)
  end

  desc "Post-release"
  private_lane :post_release do |options|
    version = options[:version].to_s
    changelog = options[:changelog]
    tag = "#{version}"

    sh('bundle', 'exec', 'swift', 'package', 'update')

    write_changelog(changelog: changelog, path: 'CHANGELOG.md')

    commit_message = "chore: finalize release #{version} [skip ci]"
    sh('git', 'commit', '-am', commit_message)

    add_git_tag(tag: tag, force: true)
    push_git_tags(tag: tag, force: true)

    # push to origin
    sh('git', 'push', 'origin', 'release')
    sh('git', 'push', 'origin', 'release:main')
  end
end
